//
//  MeViewController.m
//  zuixin
//
//  Created by QJY on 14-8-18.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
// lixi

#import "MeViewController.h"
#import "Header.h"
#import "NetAccess.h"
#import "CloseViewController.h"
#import "KefuViewController.h"
#import "ZifViewController.h"
#import "XiugViewController.h"
#import "HgViewController.h"
#import "LogViewController.h"
#import "MicroWebsiteViewController.h"
#import "MicroMallViewController.h"
#import "AboutusViewController.h"
#import "SetingUpViewController.h"
#import "MakingMoneyViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"

@interface MeViewController ()<UIScrollViewDelegate,SDWebImageManagerDelegate>

@end

@implementation MeViewController
#define AP_YES @"http://api2.ixincall.com/api/agent/clientinfo?userid=2&os=2"
//#define APP_Download @"最新版本号为:1.0.0"
{
    NetAccess *_net;
    MBProgressHUD* pro;
    int currentVersion;
    NSString *_Version;
    NSString *_urlt;
    NSUserDefaults *users;
    NSUserDefaults *myUserDefaults;
    UIImageView*_imgV;
    NSArray *_sdt;
    NSArray*_iconNameArry;
    NSString*_versionStr;
    UIScrollView*scrollViews;
    UIPageControl*page;
    NSMutableArray *imgArry;
    NSMutableArray *imgArry1;
    NSMutableArray *imgArry11;
    NSString *userId;
    NSString*_name;
    NSString*_word;
    
    BOOL panduan;
    
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        users =[NSUserDefaults standardUserDefaults];
        myUserDefaults=[NSUserDefaults standardUserDefaults];
        _sdt =[[NSArray alloc]initWithObjects:@"gcheck.png",@"guanwang.png",@"shangcheng.png",@"gengxin.png",@"makemoney",@"shezhi.png", nil];
        _iconNameArry=@[@"余额查询",@"微官网",@"微商城",@"检查更新",@"充流量",@"设置"];

        imgArry1=[[NSMutableArray alloc]init];
        imgArry11=[@[@"banner"]mutableCopy];
        imgArry=[@[@"banner"]mutableCopy];
    }
    return self;
}
-(void)virds
{
    if(IOS7)
    {
        self.automaticallyAdjustsScrollViewInsets =NO;
        // 不透明的操作栏<br
        self.extendedLayoutIncludesOpaqueBars =NO;
        //视图控制器，四条边不指定
        self.edgesForExtendedLayout =UIRectEdgeNone;
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
}
//-(void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    [self controllersd];
//}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title=@"广场";
    _versionStr= [[NSUserDefaults standardUserDefaults]objectForKey:@"Version"];
    NSLog(@"dadwwwwwa%@",_versionStr);
    NSLog(@"dada%lu",(unsigned long)_sdt.count);
    _net = [NetAccess sharedNetAccess];
    [self setNavigation];
    [self addImageView];
    [self goingLayout];
    
    
    
}
-(void)setNavigation
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navgationbar.png"] forBarMetrics: UIBarMetricsDefault];
    NSDictionary *navTitleArr = [NSDictionary dictionaryWithObjectsAndKeys:
                                 //title字体－title字体颜色
                                 [UIFont boldSystemFontOfSize:23],UITextAttributeFont,
                                 [UIColor whiteColor],UITextAttributeTextColor ,nil];
    [self.navigationController.navigationBar setTitleTextAttributes:navTitleArr];
    // Do any additional setup after loading the view.
    [self virds];
    self.view.backgroundColor =[UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1];
    
    UIButton*btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 20, 54, 44);
    [btn setTitle:@"刷新" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClickkk:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*bbj=[[UIBarButtonItem alloc]initWithCustomView:btn];
    bbj.tag=25;
    
    //  self.navigationItem.rightBarButtonItem=bbj;
}
-(void)btnClickkk:(UIButton*)sender
{
    if (imgArry1.count) {
        panduan=YES;
        
        NSLog(@"5555%@",imgArry1);
        NSLog(@"你还吗");
        [self addImageView];
    }
    else
    {
        NSLog(@"nhamahajsh啥");
    }
    
}



-(void)addImageView
{
    
    //imgArry1=[[NSUserDefaults standardUserDefaults]objectForKey:@"ImageArry"];
    
    scrollViews=[[UIScrollView alloc]init];
    [self.view addSubview:scrollViews];
    scrollViews.delegate=self;
    scrollViews.showsVerticalScrollIndicator=NO;
    scrollViews.showsHorizontalScrollIndicator=NO;
    scrollViews.pagingEnabled=YES;
    if(DeviceHeight==568)
    {
        scrollViews.frame=CGRectMake(0, 0, 320, 200);
    }
    else
    {
        scrollViews.frame=CGRectMake(0, 0, 320, 170);
    }
    
    
    
    
    
    scrollViews.contentSize=CGSizeMake(320*imgArry.count, scrollViews.frame.size.height);
    // if (imgArry.count>0&&imgArry) {
    
    
    for (int i=0; i<imgArry.count; i++) {
        UIImageView*imgView=[[UIImageView alloc]init];
        imgView.frame=CGRectMake(320*i, 0, 320, scrollViews.frame.size.height);
        // imgView.contentMode=UIViewContentModeScaleAspectFit;
        if (DeviceHeight==568)
        {
            imgView.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",imgArry[i]]] ;
        }
        else
        {
            imgView.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",imgArry11[i]]] ;
        }
        
        [scrollViews addSubview:imgView];
    }
    page=[[UIPageControl alloc]initWithFrame:CGRectMake(0, scrollViews.frame.size.height-20, 320, 20)];
    page.numberOfPages=imgArry.count;
    
    //        if (panduan) {
    //            NSURL *url=[NSURL URLWithString:imgArry1[i]];
    //            if (DeviceHeight==568) {
    //                [imgView sd_setImageWithURL:url
    //                           placeholderImage:[UIImage imageNamed:@"2.jpg"]];
    //            }
    //            else
    //            {
    //                [imgView sd_setImageWithURL:url
    //                           placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    //            }
    //            page.numberOfPages=imgArry1.count;
    //            }
    //
    //            else
    //        {
    //            if (DeviceHeight==568) {
    //                imgView.image=[UIImage imageNamed:@"2.jpg"];
    //               }
    //            else
    //            {
    //              imgView.image=[UIImage imageNamed:@"1.jpg"];
    //            }
    //
    
    // imgView.backgroundColor=[UIColor redColor];
    
    
    
    
    
    //    else
    //    {
    //        UIImageView*imgView=[[UIImageView alloc]init];
    //        imgView.frame=CGRectMake(0, 0, 320, scrollViews.frame.size.height);
    //        imgView.image=[UIImage imageNamed:@"1.jpg"];
    //        [scrollViews addSubview:imgView];
    //    }
    page.currentPage=0;
    page.userInteractionEnabled=NO;
    page.currentPageIndicatorTintColor=[UIColor blackColor];
    
    [NSTimer scheduledTimerWithTimeInterval:4.0f target:self selector:@selector(changeImageView) userInfo:nil repeats:YES];
    
    [self.view addSubview:page ];
    
}
-(void)changeImageView
{
    if (scrollViews.contentOffset.x<320*(imgArry.count-1)) {
        scrollViews.contentOffset=CGPointMake(scrollViews.contentOffset.x+320, 0);
    }else{
        scrollViews.contentOffset=CGPointMake(0, 0);
    }
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int pageNumber=scrollView.contentOffset.x/320;
    
    page.currentPage=pageNumber;
    
    
    
    
}
-(void)goingLayout
{
    
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, scrollViews.frame.size.height, 320, DeviceHeight-scrollViews.frame.size.height-64-44)];
    //    view.backgroundColor= [UIColor blueColor];
    [self.view addSubview:view ];
    if(DeviceHeight==568)
    {
        for (int i=0; i<_sdt.count; i++)
        {
            UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
            
            button.tag=100+i;
            //button.backgroundColor=[UIColor redColor];
            
            button.frame=CGRectMake(41+(40+60)*(i%3),30+ (30+60)*(i/3), 60, 60);
            
            [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",_sdt[i]]] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside ];
            
            [view addSubview:button];
            UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(40+(40+60)*(i%3), 80+(60+30)*(i/3), 60, 30)];
            
            label.backgroundColor=[UIColor clearColor];
            label.text=_iconNameArry[i];
            
            label.font=[UIFont systemFontOfSize:14];
            label.textAlignment=UITextAlignmentCenter;
            [view addSubview:label];
        }
        //        UIButton*btn=[UIButton buttonWithType:UIButtonTypeCustom];
        //        btn.frame=CGRectMake(40+(40+60)*(8%3),80+ (60+30)*(8/3), 60, 30);
        //        [btn setTitle:@"切换账号" forState:UIControlStateNormal];
        //        btn.backgroundColor=[UIColor blueColor];
        //        btn.tag=1065;
        //        [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        //        btn.adjustsImageWhenDisabled=YES;
        //        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        //        [view addSubview:btn];
    }
    else
    {
        for (int i=0; i<_sdt.count; i++)
        {
            UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
            button.tag=100+i;
            
            
            
            button.frame=CGRectMake(40+(40+50)*(i%3),20+ (20+50)*(i/3), 50, 50);
            
            [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",_sdt[i]]] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside ];
            [view addSubview:button];
            UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(40+(40+50)*(i%3), 70+(50+20)*(i/3), 50, 20)];
            
            label.backgroundColor=[UIColor clearColor];
            label.text=_iconNameArry[i];
            label.font=[UIFont systemFontOfSize:12];
            label.textAlignment=UITextAlignmentCenter;
            [view addSubview:label];
        }
        
    }
    
    
}

-(void)btnClick:(UIButton *)bbi
{
    if(bbi.tag ==100)
    {
        [self.navigationController pushViewController:[CloseViewController alloc] animated:YES];
    }
    if(bbi.tag ==101)
    {
        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"暂未开放，敬请期待" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
        //[self.navigationController pushViewController:[MakingMoneyViewController alloc] animated:YES];
    }
    if(bbi.tag ==102)
    {
        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"暂未开放，敬请期待" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
        //        [self.navigationController pushViewController:[MicroMallViewController alloc] animated:YES];
    }
    
    if(bbi.tag ==112)
    {
        [self.navigationController pushViewController:[MicroWebsiteViewController alloc] animated:YES];
    }
    if(bbi.tag==103)
    {[self match];
        if(![_net haveNet])
        {[pro removeFromSuperview];
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }else{
            [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(getNewVersion:) object:nil];
            [self performSelector:@selector(getNewVersion:) withObject:nil afterDelay:0.5f];
        }
        
    }
    
    
    if(bbi.tag ==1005)
    {
        if(![_net haveNet])
        {
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            
        }
        else
        {
            [self.navigationController pushViewController:[ZifViewController alloc] animated:YES];
        }
    }
    
    if(bbi.tag ==104)
    {
        
//        [self.navigationController pushViewController:[[AboutusViewController alloc]init] animated:YES];
            [self.navigationController pushViewController:[MicroWebsiteViewController alloc] animated:YES];
    }
    if(bbi.tag ==105)
    {
        [self.navigationController pushViewController:[[SetingUpViewController alloc]init] animated:YES];
    }
    
    
    
    if(bbi.tag ==1035)
    {
        [self.navigationController pushViewController:[KefuViewController alloc] animated:YES];
    }
    if(bbi.tag ==1065)
    {
        [users removeObjectForKey:@"users"];
        [users synchronize];
        [myUserDefaults removeObjectForKey:@"tellDemol"];
        [myUserDefaults synchronize];
        [self presentViewController:[LogViewController
                                     alloc] animated:YES completion:^{
            //[self .view removeFromSuperview];
        }];
    }
    if(bbi.tag ==1013)
    {
        [self showMessageView];
    }
    if(bbi.tag ==1024)
    {
        [self.navigationController pushViewController:[ZifViewController alloc] animated:YES];
    }
}
- (void)getNewVersion:(id)sender
{
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://oemapi2.leehuu.cn/api/agent/clientinfo?userid=2645421&os=2"]];
    if (data==nil) {
        return;
    }
    else
    {
        NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"豆荚%@",dict);
        //通过公告获取网络信息最新版本号
        _Version =[dict objectForKey:@"VersionNumber"];
        _urlt =[dict objectForKey:@"Url"];
        
        
        [self checkUpdate];
    }}
-(void)match
{
    pro = [[MBProgressHUD alloc] initWithView:self.view];
    pro.labelText = @"请稍后..";
    pro.mode = MBProgressHUDModeText;
    [self.view addSubview:pro];
    [pro showAnimated:YES whileExecutingBlock:^{
        [NSThread sleepForTimeInterval:20.0];
    } completionBlock:^{
    }];
}
-(void)checkUpdate
{
    
    [pro removeFromSuperview];
    NSLog(@"ss%@",_versionStr);
    //获取最新版本
    NSString * sLastVersion= [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey]];//取当前的版本
    NSString* newsLastVersion=[sLastVersion substringToIndex:5];
    if (!(_Version==nil||[_Version isEqual:[NSNull null]])){
        
        
        NSString *sLastVersion1=[NSString stringWithFormat:@"%@%@%@",[sLastVersion substringToIndex:1],[sLastVersion substringWithRange:NSMakeRange(2, 1)],[sLastVersion substringWithRange:NSMakeRange(4, 1)]];
        
        NSString *_Version1=[NSString stringWithFormat:@"%@%@%@",[_Version substringToIndex:1],[_Version substringWithRange:NSMakeRange(2, 1)],[_Version substringWithRange:NSMakeRange(4, 1)]];
        NSLog(@"qq%@    ww%@",sLastVersion1,_Version1);
        
        if ([sLastVersion1 intValue]< [_Version1 intValue])
        {
            NSString*mess=[NSString stringWithFormat:@"最新版本号为:%@\n当前版本号为:%@",_Version,newsLastVersion];
            UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"升级提示"message:mess delegate:self cancelButtonTitle:@"以后再说" otherButtonTitles:@"马上更新",nil];
            av.delegate=self;
            av.tag =1000;
            [av show];
            
        }
        else
        {
            UIAlertView *v =[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"当前版本:%@",newsLastVersion]message:@"已是最新的版本，无需下载" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [v show];
        }
        
        
    }else
    {
        UIAlertView *v =[[UIAlertView alloc] initWithTitle:@"提醒" message:@"服务不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v show];
        
    }
}
//前往更新
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag ==1000)
        
    {
        //        NSString *strUrl = [_urlt stringByReplacingOccurrencesOfString:@"\" withString:@""]        _urlt
        if (buttonIndex != [alertView cancelButtonIndex])
        {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_urlt ]];
            NSLog(@"1111111%@",_urlt);
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}
- (void)showMessageView
{
    if( [MFMessageComposeViewController canSendText] ){
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc]init];
        controller.body = @"我正在使用爱信免费网络电话，快点来加入吧！www.ixincall.com/app";
        controller.messageComposeDelegate = self;
        //
        if(IOS7)
        {
            [self presentViewController:controller animated:YES completion:^{
                
            }];
        }else
        {
            [self presentModalViewController:controller animated:YES];
        }
        
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:@"推介好友"];
    }else{
        [self alertWithTitle:@"提示信息" msg:@"设备没有短信功能"];
    }
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    if(IOS7)
    {
        [controller dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    else
    {
        [controller dismissModalViewControllerAnimated:NO];
    }
    
    switch ( result ) {
            
        case MessageComposeResultCancelled:
            
            [self alertWithTitle:@"提示信息" msg:@"发送取消"];
            break;
        case MessageComposeResultFailed:
            [self alertWithTitle:@"提示信息" msg:@"发送失败"];
            break;
        case MessageComposeResultSent:
            [self alertWithTitle:@"提示信息" msg:@"发送成功"];
            break;
        default:
            break;
    }
}
- (void) alertWithTitle:(NSString *)title msg:(NSString *)msg {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"确定", nil];
    [alert show];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
